import {
	shallowRef,
} from 'vue';
import {
	beforeProcessor,
	noop,
} from '../../util/common/index';
import {
	MySet,
} from '../../util/polyfill';

export default function(
	{
		key,
		value,
		active,
		disabled,
		aloneActive,
		beforeChange,
		aloneValue,
		emit,
	}:any,
){
	const rootRef = shallowRef<HTMLElement>();
	//region 值类型
	const modelType = ():'set' | 'array' | false => {
		if(key() !== undefined){
			const val = value();
			if(Array.isArray(val)){
				return 'array';
			}else if(val instanceof MySet){
				return 'set';
			}
		}
		return false;
	};
	//endregion
	//region 状态
	const activeStatus = ():any => {
		const activeVal = active();
		if(activeVal == null){
			const val = value();
			const type = modelType();
			if(type === 'array'){
				return val.indexOf(key()) > -1;
			}else if(type === 'set'){
				return val.has(key());
			}
			return aloneActive(val);
		}
		return activeVal;
	};
	//endregion
	//region 点击事件
	const clickFn = () => {
		if(disabled()) return;
		rootRef.value!.blur();
		const type = modelType();
		const isActive = activeStatus();
		if(type){
			const keyVal = key();
			const val = value();
			beforeProcessor(beforeChange?.({key:keyVal,active:isActive})).then(() => {
				if(type === 'array'){
					if(isActive){
						emit('input',val.filter((e:any) => e !== keyVal));
					}else{
						emit('input',val.concat([keyVal]));
					}
				}else if(type === 'set'){
					if(isActive){
						val.delete(keyVal);
					}else{
						val.add(keyVal);
					}
					emit('input',val);
				}
				if(isActive){
					emit('inactive',keyVal);
				}else{
					emit('active',keyVal);
				}
			}).catch(noop);
		}else{
			beforeProcessor(beforeChange?.(isActive)).then(() => {
				emit('input',aloneValue(isActive));
			}).catch(noop);
		}
	};
	//endregion
	return {
		activeStatus,
		clickFn,
		rootRef,
	};
}